/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core;

import com.googlecode.actorom.CompletableFutureResult;
import com.googlecode.actorom.support.ActorExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.jcip.annotations.ThreadSafe;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class CoreFutureResult implements CompletableFutureResult {

    private final long timeoutInNanos;
    private final long startTimeInNanos;
    private final Lock lock;
    private final Condition signal;
    private boolean completed;
    private Object result;
    private ActorExecutionException exception;

    public CoreFutureResult(long timeoutInNanos) {
        this.timeoutInNanos = timeoutInNanos;
        startTimeInNanos = currentTimeInNanos();
        lock = new ReentrantLock();
        signal = lock.newCondition();
    }

    public long getTimeoutInNanos() {
        return timeoutInNanos;
    }

    public void await() {
        try {
            lock.lock();
            long wait = timeoutInNanos - (currentTimeInNanos() - startTimeInNanos);
            while (!completed && wait > 0) {
                long start = currentTimeInNanos();
                try {
                    wait = signal.awaitNanos(wait);
                } catch (InterruptedException ex) {
                    wait = wait - (currentTimeInNanos() - start);
                }
            }
        } finally {
            lock.unlock();
        }
    }

    public boolean isCompleted() {
        try {
            lock.lock();
            return completed;
        } finally {
            lock.unlock();
        }
    }

    public boolean isExpired() {
        try {
            lock.lock();
            return (timeoutInNanos - (currentTimeInNanos() - startTimeInNanos)) <= 0;
        } finally {
            lock.unlock();
        }
    }

    public Object getResult() {
        try {
            lock.lock();
            return result;
        } finally {
            lock.unlock();
        }
    }

    public ActorExecutionException getException() {
        try {
            lock.lock();
            return exception;
        } finally {
            lock.unlock();
        }
    }

    public void completeWithResult(Object result) {
        try {
            lock.lock();
            if (!completed) {
                completed = true;
                this.result = result;
            }
        } finally {
            signal.signalAll();
            lock.unlock();
        }
    }

    public void completeWithException(ActorExecutionException exception) {
        try {
            lock.lock();
            if (!completed) {
                completed = true;
                this.exception = exception;
            }
        } finally {
            signal.signalAll();
            lock.unlock();
        }
    }

    private long currentTimeInNanos() {
        return TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis());
    }
}
